package com.caifu.controller.drugs;

import com.alibaba.excel.EasyExcel;
import com.alibaba.fastjson.JSON;
import com.caifu.controller.AbstractController;
import com.caifu.excel.*;
import com.caifu.mapper.SysOrganizationMapper;
import com.caifu.pojo.SysOrganization;
import com.caifu.pojo.SysUser;
import com.caifu.service.YlMeicineDistributionService;
import com.caifu.service.YlUserMedicineService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 导出药品发放、登记记录
 *
 * @author tww
 * ClassName: MeicineDistributionExcelController.java、
 * createTime: 2020年11月19日 09:57:46
 **/
@Controller
@RequestMapping("excel")
public class MeicineDistributionExcelController extends AbstractController {

    private static final Logger logger = LoggerFactory.getLogger(MeicineDistributionExcelController.class);

    @Resource
    private YlMeicineDistributionService ylMeicineDistributionService;

    @Resource
    private YlUserMedicineService ylUserMedicineService;

    @Resource
    private SysOrganizationMapper sysOrganizationMapper;


    /**
     * 导出药物发放表 文件下载并且失败的时候返回json（默认失败了会返回一个有部分数据的Excel）
     */
    @GetMapping("exportExcel")
    public void exportExcel(String userNo, HttpServletResponse response) throws IOException {

        try {
            response.setContentType("application/vnd.ms-excel");
            response.setCharacterEncoding("utf-8");
            String name = String.valueOf(System.currentTimeMillis());
            // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
            String fileName = URLEncoder.encode(name, "UTF-8");
            response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");


            EasyExcel.write(response.getOutputStream())
                    .autoCloseStream(Boolean.FALSE)
                    .head(ylMeicineDistributionService.getExcelHead())
                    .registerWriteHandler(new Custemhandler())
                    .useDefaultStyle(true).relativeHeadRowIndex(3)
                    .sheet("药品发放表")
                    .doWrite(ylMeicineDistributionService.getExcelData(userNo));
        } catch (Exception e) {
            e.printStackTrace();
            // 重置response
            response.reset();
            response.setContentType("application/json");
            response.setCharacterEncoding("utf-8");
            Map<String, Object> map = new HashMap<>(10);
            map.put("status", "failure");
            map.put("message", "下载文件失败" + e.getMessage());
            response.getWriter().println(JSON.toJSONString(map));
        }
    }

    /**
     * 导出药物发放表 文件下载并且失败的时候返回json（默认失败了会返回一个有部分数据的Excel）
     */
    @GetMapping("exportExcel2")
    public void exportExcel2(String userNo, HttpServletResponse response) throws IOException {
        SysUser user = getUser();
        SysOrganization sysOrganization = sysOrganizationMapper.selectById(user.getCurrentPensionNo());
        try {
            response.setContentType("application/vnd.ms-excel");
            response.setCharacterEncoding("utf-8");
            String name = String.valueOf(System.currentTimeMillis());
            // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
            String fileName = URLEncoder.encode(name, "UTF-8");
            response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");


            EasyExcel.write(response.getOutputStream(), ExcelMeicineDistribution.class)
                    .autoCloseStream(Boolean.FALSE)
                    .head(ExcelMeicineDistribution.class)
                    .registerWriteHandler(new GrantHandler(userNo, sysOrganization.getOrgName()))
                    .sheet("药品发放表")
                    .useDefaultStyle(true).relativeHeadRowIndex(3)
                    .doWrite(ylMeicineDistributionService.getExcelData(userNo));
        } catch (Exception e) {
            e.printStackTrace();
            // 重置response
            response.reset();
            response.setContentType("application/json");
            response.setCharacterEncoding("utf-8");
            Map<String, Object> map = new HashMap<>(10);
            map.put("status", "failure");
            map.put("message", "下载文件失败" + e.getMessage());
            response.getWriter().println(JSON.toJSONString(map));
        }
    }


    /**
     * 导出药物登记表 文件下载并且失败的时候返回json（默认失败了会返回一个有部分数据的Excel）
     */
    @GetMapping("exportRegExcel")
    public void exportRegExcel(String userNo, HttpServletResponse response) throws IOException {
        SysUser user = getUser();
        SysOrganization sysOrganization = sysOrganizationMapper.selectById(user.getCurrentPensionNo());
        try {
            response.setContentType("application/vnd.ms-excel");
            response.setCharacterEncoding("utf-8");
            String name = String.valueOf(System.currentTimeMillis());
            // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
            String fileName = URLEncoder.encode(name, "UTF-8");
            response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");

            EasyExcel.write(response.getOutputStream(), ExcelMedicine.class)
                    .autoCloseStream(Boolean.FALSE)
                    .head(ExcelMedicine.class)
                    .registerWriteHandler(new RegHandler(userNo, sysOrganization.getOrgName()))
                    .sheet("药品登记表")
                    .useDefaultStyle(true).relativeHeadRowIndex(3)
                    .doWrite(ylUserMedicineService.getExcelData(userNo));
        } catch (Exception e) {
            e.printStackTrace();
            // 重置response
            response.reset();
            response.setContentType("application/json");
            response.setCharacterEncoding("utf-8");
            Map<String, Object> map = new HashMap<>(10);
            map.put("status", "failure");
            map.put("message", "下载文件失败" + e.getMessage());
            response.getWriter().println(JSON.toJSONString(map));
        }
    }


    private List<List<String>> head() {
        List<List<String>> list = new ArrayList<List<String>>();
        List<String> head0 = new ArrayList<String>();
        head0.add("字符串" + System.currentTimeMillis());
        List<String> head1 = new ArrayList<String>();
        head1.add("数字" + System.currentTimeMillis());
        List<String> head2 = new ArrayList<String>();
        head2.add("日期" + System.currentTimeMillis());
        list.add(head0);
        list.add(head1);
        list.add(head2);
        return list;
    }

}
